package com.shujujiegou.栈.增强栈的实现;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 *  1. 动态扩容
 *  2. 存储任意类型
 */
public class ArrayStack {
    private Object array[];
    private int size;
    private int top;

    public ArrayStack() {
        this.array = new Object[10];
        this.size = 10;
        this.top = -1;
    }

    public ArrayStack(int size) {
        if(size < 0) {
            throw new IllegalArgumentException("栈的初始容量不能小于0：" + size);
        }

        this.size = size;
        this.array = new Object[size];
        this.top = -1;
    }

    // 压入元素
    public Object push(Object object) {
        isGrow(this.top + 1);
        this.array[++top] = object;
        return object;
    }

    // 弹出栈顶元素
    public Object pop() {
        if(isEmpty()) {
            throw new EmptyStackException();
        }

        return this.array[this.top--];
    }

    // 获取栈顶元素
    public Object peek() {
        if(isEmpty()) {
            throw new EmptyStackException();
        }

        return this.array[this.top];
    }

    // 删除栈顶元素
    public void remove() {
        if(isEmpty()) {
            throw new EmptyStackException();
        }

        this.array[top] = null;
        this.top --;
    }

    // 判断栈是否为空
    public boolean isEmpty() {
        return (top == -1);
    }

    // 判断是否应该扩容--》扩容
    private boolean isGrow(int top) {
        if(top >= this.size) {
            // 定义扩容后栈的总量
            int newSize = 0;
            // 每次自动扩容两倍，如果超出int类型表示的最大数值，将int最大数值赋值给newSize
            if((this.size << 1) - Integer.MAX_VALUE > 0) {
                newSize = Integer.MAX_VALUE;
            } else {
                newSize = this.size << 1;
            }

            this.size = newSize;
            this.array = Arrays.copyOf(this.array, this.size);
            return true;
        } else {
            return false;
        }
    }
}
